﻿var userId = null;
var jsonResponse = null;
var lastPartial;
var lastStatus;
var updateList = new UpdateList();

$(document).ready(function($) {

    // variable used to detect if form being edited
    var editing = false;

    $("#inStatus").bind("change", function() {
        $("#inStatusForm").submit();
    });

    $("#officeStatus").bind("change", function() {
        $("#inStatusForm").submit();
    });

    getUserId();
    initializeUpdates();

    setInterval(function() {
        getPartialUpdates();
    }, 15000);

    setInterval(function() {
        getProfileUpdates();
    }, 30000);
});

function getUserId() {
    $.getJSON("FormsAuthentication/GetUserId/"
        , {}
        , function(data) {
        userId = data.ProviderUserKey;
    });
}

function initializeUpdates() {
    $.ajax({
        url: "Updates/Get/",
        cache: false,
        dataType: "json",
        success: function(response) {
            lastPartial = response.Queried;
            lastStatus  = response.Queried;
            $.each(response.Updates, function(index, update) {

                updateList.addUpdate(index, update, false);
            });
        }
    });
}

function getPartialUpdates() {
    $.ajax({
        url: "Updates/Get/",
        data: "lastPartial=" + lastPartial,
        cache: false,
        dataType: "json",
        success: function(response) {
            if (response.Status == 200) {
                lastPartial = response.Queried;
                $.each(response.Updates, function(index, update) {
                    switch (update.Activity) {
                        case "Insert":
                            updateList.addUpdate(updateList.updates.length, update, true);
                            break;
                        case "Update":
                            updateList.updateUpdate(update.Id, update);
                            break;
                        case "Delete":
                            updateList.deleteUpdate(update.Id);
                            break;
                        default:
                            break;
                    }
                });
            } else if (response.Status == 100) {

            }
        }
    });
}

function getProfileUpdates() {
    $.ajax({
        url: "Updates/GetProfiles/",
        data: "lastStatus=" + lastStatus,
        cache: false,
        dataType: "json",
        success: function(response) {
            lastStatus = response.Queried;
            $.each(response.Profiles, function(index, profile) {
                updateProfile(profile);
            });
        }
    });
}

function updateProfile(profile) {

    // Update elapsed time since last status update
    $("#" + profile.UserName + "Elapsed").text("just recently");

    // Update InStatus
    if (profile.InStatus) {
        if (profile.OfficeStatus) {
            $("#" + profile.UserName + "InOutStatus").text("In the Office");
        } else {
            $("#" + profile.UserName + "InOutStatus").text("In, working remotely");
        }
    } else {
        $("#" + profile.UserName + "InOutStatus").text("Out");
    }

    // Update Contact Number
    if (profile.InStatus) {
        if (profile.OfficeStatus) {
            $("#" + profile.UserName + "Contact").text(
                            "Contact Me @ "
                            + "(" + profile.OfficePhone.substring(0, 3)  + ") "
                            + profile.OfficePhone.substring(3, 6) + "-"
                            + profile.OfficePhone.substring(6));
        } else {
        $("#" + profile.UserName + "Contact").text(
                            "Contact Me @ "
                            + "(" + profile.RemotePhone.substring(0, 3) + ") "
                            + profile.RemotePhone.substring(3, 6) + "-"
                            + profile.RemotePhone.substring(6));
        }
    } else {
        $("#" + profile.UserName + "Contact").text(
                            "Contact Me @ "
                            + "(" + profile.RemotePhone.substring(0, 3) + ") "
                            + profile.RemotePhone.substring(3, 6) + "-"
                            + profile.RemotePhone.substring(6));
    }

    // Update Status
    $("#" + profile.UserName + "Status").text(profile.Status);
    
    // Flash the name of the user whose profile was updated
    flash("#" + profile.UserName);
}

function submitUpdate(text) {
}

UpdateList.prototype.addUpdate = UpdateList_addUpdate;
UpdateList.prototype.updateUpdate = UpdateList_updateUpdate;
UpdateList.prototype.deleteUpdate = UpdateList_deleteUpdate;

function UpdateList_addUpdate(index, update, isPartial) {

    this.updates[index] = new Update(update.Id, update.DateTimeEntered, update.UserId, update.UserName, update.UpdateText);

    var updateDate = parseDate(update.DateTimeEntered);
    var updateMonth = updateDate.getMonth();
    var updateDay = updateDate.getDate();
    var updateYear = updateDate.getFullYear();

    if ((this.date == null || this.date.toDateString() != updateDate.toDateString()) && !isPartial) {

        if (this.month == updateMonth
            && this.day == updateDay
            && this.year == updateYear) {

            $("#updates ul#groupUpdates").prepend(
                "<li id='today' class='listheader'>"
                    + "<span style='background-color: Yellow; padding: 2px 1em 2px 2em;'>TODAY</span>"
                + "</li>");
        } else if (this.month == updateMonth
                    && this.day == updateDay - 1
                    && this.year == updateYear) {

            $("#updates ul#groupUpdates").prepend(
                "<li id='yesterday' class='listheader'>"
                    + "<span style='padding: 2px 1em 2px 5px; text-decoration: underline;'>YESTERDAY</span>"
                + "</li>");
        } else {

            $("#updates ul#groupUpdates").prepend(
                "<li id='" + updateDate.toDateString() + "' class='listheader'>"
                    + "<span style='padding: 2px 1em 2px 5px; text-decoration: underline;'>"
                        + updateDate.toDateString()
                    + "</span>"
                + "</li>");
        }
    }

    $("#updates ul#groupUpdates li.listheader:first").after(
        "<li id='" + update.Id + "Wrapper' style='display:none;'>"
            + "<span style='font-weight: bold; display: inline;'>"
                + "<a href='Updates/UserDetail/"
                    + update.UserId + "'>" + update.UserName + "</a>:"
            + "</span> "
            + "<span id='" + update.Id + "' style='background-color: none;'>"
                + formatText(update.UpdateText)
            + "</span>");

    if (userId == update.UserId) {

        $("#updates ul#groupUpdates li.listheader:first + li").append(
                "&nbsp;&nbsp;<a style='font-size: 0.75em;' id='editLink" + update.Id + "' "
                    + "href='javascript:editUpdate(" + update.Id + ")'>edit</a>"
                + "<span id='edit" + update.Id + "' style='font-size: 0.75em; display: none;'>"
                    + "<form action='Updates/SaveEdit/" + update.Id + "'>"
                        + "<input method='post' type='text' name='UpdateText' value='" + update.UpdateText + "' />"
                        + "&nbsp;&nbsp;<a href='javascript:cancelEdit(" + update.Id + ")'>cancel</a> "
                        + "&nbsp;<a href='Updates/DeleteUpdate/" + update.Id + "'>delete</a>"
                    + "</form>"
                + "</span>"
            + "</li>").show("slow");
            
            if (isPartial) {
                
                var selector = "#" + update.Id;
                flash(selector);
            }

    } else {

        $("#updates ul#groupUpdates li.listheader:first + li").append("</li>").show("Slow");
        
        if (isPartial) {
            
            var selector = "#" + update.Id;
            flash(selector);
        }
    }

    if (isPartial) {
        $("#" + update.UserName + "Updates").prepend(
            "<li>" + formatText(update.UpdateText) + "</li>");

        $("#" + update.UserName + "Updates li:last").remove();
    }

    this.date = updateDate;
}

function UpdateList_updateUpdate(index, update) {
    flash("#" + index);
    setTimeout(function() {
        $("#" + index).html(formatText(update.UpdateText));
        $("#" + index + "MemberUpdatesWrapper").html(formatText(update.UpdateText));
    }, 400);
}

function UpdateList_deleteUpdate(index) {
    flash("#" + index + "Wrapper");
    setTimeout(function() {
        $("#" + index + "Wrapper").remove();
        $("#" + index + "MemberUpdatesWrapper").remove();
    }, 400);
}

function formatText(str) {

    return str.replace(/(\w+):\/\/[\S]+(\b|$)/gim,
                '<a href="$&" class="updateLink" target="_blank">$&</a>')
            .replace(/([^\/])(www[\S]+(\b|$))/gim,
                '$1<a href="http://$2" class="updateLink" target="_blank">$2</a>')
            .replace(/^(www[\S]+(\b|$))/gim,
                '<a href="http://$1" class="updateLink" target="_blank">$1</a>');

}

function flash(selector) {
    $(selector)
        .css('opacity', 0)
        .animate({ backgroundColor: 'khaki', opacity: 1.0 }, 800)
        .animate({ backgroundColor: 'transparent' }, 350);
        
}

function parseDate(data) {
    var array = data.split('(');
    array = array[1].split(')');

    var date = new Date(parseInt(array[0]));

    return date;
}

function Update(id                  // Update Id determined by database identity column
                , dateTimeEntered   // The Date and Time the Update was created
                , userId            // The UserId of the User who entered the Update
                , userName          // The UserName of the User who entered the Update
                , updateText) {     // The Text of the Update

    this.id = id;
    this.dateTimeEntered = dateTimeEntered;
    this.userId = userId;
    this.userName = userName;
    this.updateText = updateText;

    this.toString = function() {

        return "{" +
            this.id + ", " +
            this.dateTimeEntered + ", " +
            this.userId + ", " +
            this.userName + ", " +
            this.updateText + "} ";
    }
}

function UpdateList() {
    this.date;
    this.dateObj = new Date();
    this.month = this.dateObj.getMonth();
    this.day = this.dateObj.getDate();
    this.year = this.dateObj.getFullYear();

    this.updates = [];
}

function Profile(userId                 // The UserId of the User who updated their Profile
                , dateTimeLastUpdated   // The Date and Time the Profile was updated
                , userName              // The UserName of the User who updated their Profile
                , status                // The Status of the Profile
                , inStatus              // The InStatus of the Profile
                , officeStatus) {       // The OfficeStatus of the Profile

    this.userId                 = userId;
    this.dateTimeLastUpdated    = dateTimeLastUpdated;
    this.userName               = userName;
    this.status                 = status;
    this.inStatus               = inStatus;
    this.officeStatus           = officeStatus;

    this.toString = function() {

        return "{" +
            this.userId + ", " +
            this.dateTimeLastUpdated + ", " +
            this.userName + ", " +
            this.status + ", " +
            this.inStatus + ", " +
            this.officeStatus + "} ";
    }
}


$(document).unload(function($) {
    $("#inStatus").unbind();
    $("#officeStatus").unbind();
});

function editUpdate(id) {

    $("#" + id.toString()).css("display", "none");
    $("#editLink" + id.toString()).css("display", "none");
    $("#elapsed" + id.toString()).css("display", "none");
    $("#edit" + id.toString()).css("display", "inline");
    editing = true;
}

function cancelEdit(id) {

    $("#edit" + id.toString()).css("display", "none");
    $("#" + id.toString()).css("display", "inline");
    $("#editLink" + id.toString()).css("display", "inline");
    $("#elapsed" + id.toString()).css("display", "inline");
    editing = false;
}